package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional//事务
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public ResultInfo login(String username, String password) {
        //1.根据username调用mapper查询
        Employee employee = employeeMapper.findByUsername(username);
        if (employee == null) {
            return ResultInfo.error("此用户不存在");
        }

        //2.将传入的password进行加密然后与查询到的密码比对
        String passwordWithMd5 = SecureUtil.md5(password);
        if (!StringUtils.equals(passwordWithMd5, employee.getPassword())) {
            return ResultInfo.error("密码错误!");
        }

        //3.查看查询到的status是否是0(禁用状态)
        if (employee.getStatus() == Employee.STATUS_DISABLE) {
            return ResultInfo.error("当前账号不可登录!");
        }

        //4.条件均通过,返回成功标识
        return ResultInfo.success(employee);
    }

    @Override
    public List<Employee> findByName(String name) {
        List<Employee> employeeList = employeeMapper.findByName(name);
        return employeeList;
    }

    @Override//新增
    public void save(Employee employee) {
        employee.setId(IdUtil.getSnowflake(1,1).nextId());//雪花算法生成id

        String passwordByMd5 = SecureUtil.md5("123456");
        employee.setPassword(passwordByMd5);//默认初始密码(MD5加密)

        employee.setStatus(Employee.STATUS_ENABLE);//默认正常

//        employee.setCreateTime(new Date());//创建时间
//        employee.setUpdateTime(new Date());//更新时间
//        employee.setCreateUser(1L);//创建人
//        employee.setUpdateUser(1L);//修改人

        employeeMapper.insert(employee);
    }

    @Override
    public Employee findById(Long id) {

        Employee employee = employeeMapper.findById(id);
        return employee;
    }

    @Override
    public void update(Employee employee) {
//        employee.setUpdateTime(new Date());//更新时间
//        employee.setUpdateUser(1L);//修改人

        employeeMapper.update(employee);
    }
}
